package com.wingbow.ticket;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.ServerWebSocket;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by sweet on 2017/9/27.
 */
@Slf4j
public class WebSocketVerticle extends AbstractVerticle {


    public static final String FOEMAT_HOST = "/host/(\\d+)(/?)";
    public static final String FOEMAT_TERMINAL = "/terminal/(\\d+)(/?)";

    @Override
    public void start() throws Exception {
        HttpServer httpServer = vertx.createHttpServer().websocketHandler(serverWebSocket -> {
            serverWebSocket.frameHandler(null);
            String path = serverWebSocket.path();
            log.info("client connected: sessionId:{},path:{}", serverWebSocket.textHandlerID(), path);
            Matcher hostMatcher = Pattern.compile(FOEMAT_HOST).matcher(path);
            Matcher terminalMatcher = Pattern.compile(FOEMAT_TERMINAL).matcher(path);
            if (hostMatcher.matches()) {
                final String roomId = hostMatcher.group(1);
                HostWebSocket.handle(serverWebSocket, roomId);
            } else if (terminalMatcher.matches()) {
                final String roomId = terminalMatcher.group(1);
                TerminalWebSocket.handle(serverWebSocket, roomId);
            } else {
                log.error("非法请求{}，拒绝连接", path);
                serverWebSocket.close();
                return;
            }
        });

        httpServer.listen(9099, server -> {
            if (server.succeeded()) {
                log.info("启动成功");
            } else {
                server.cause().printStackTrace();
            }
        });

        // vertx.setPeriodic(id);

        vertx.setPeriodic(5000, e -> {
            log.info("定时任务触发{}，当前存活的hostMap：{},terminalMap：{}", Thread.currentThread().getName(), Client.hostMap.size(),
                    Client.terminalMap.size());
            Client.hostMap.forEach((k, v) -> {
                ServerWebSocket serverWebSocket = v.getServerWebSocket();
                if (v.isAudit()) {
                    serverWebSocket.writePing(Buffer.buffer());
                }
            });
            Client.terminalMap.forEach((k, v) -> {
                ServerWebSocket serverWebSocket = v.getServerWebSocket();
                if (v.isAudit()) {
                    serverWebSocket.writePing(Buffer.buffer());
                }
            });
        });
    }



}
